//
//  WenZhouQuanMacro.swift
//  WenZhouQuan
//
//  Created by Meeno04 on 15/12/26.
//  Copyright © 2015年 meeno. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

public class CommonMethod:NSObject {
    
    public static let share = CommonMethod.init()
    
    private override init() { super.init() }
    
    //MARK: variable
    public   lazy var mainStoryBoard:UIStoryboard = {
        var storyBoard = UIStoryboard(name: "Main", bundle: nil)
        return storyBoard
    }()
    
    public  let formatter = DateFormatter()
    
    
    /// 把剩余时间的秒转换为字符串
    /// - Parameter second: 时间戳
    /// - Returns: 剩余时间字符串
    public func coverTime(second: Double) -> String {
        
        let date = Date(timeIntervalSince1970: second)
        if (second / Double(3600) >= 1){
            formatter.dateFormat = "HH:mm:ss"
        }else{
            formatter.dateFormat = "mm:ss"
        }
        
        let showtimeNew = formatter.string(from: date)
        return showtimeNew
    }
    
    /// 获取版本号
    public func getBundleVersion() -> String? {
        return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
    }
    
    /// 获取buildid
    public func getBundleBuild() -> Int? {
        guard let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String else {
            return nil
        }
        
        return Int.init(build)
    }
    
    
    //获取顶层VC
    
    public  static func getCurrentVC() -> UIViewController?{
        let window = UIApplication.normalLevelWindow()
        return getCurrentVC(with: window)
    }
    
    public  static func getCurrentVC(with window:UIWindow?) -> UIViewController?{
        
        func getTopCurrentVC(viewController : UIViewController?) -> UIViewController?{
            if viewController == nil {
                print("viewController is nil")
                return nil
            }
            
            if let a = viewController as? UITabBarController {
                return getTopCurrentVC(viewController: a.selectedViewController!)
            } else if let a = viewController as? UINavigationController {
                return getTopCurrentVC( viewController: a.visibleViewController)
            }
            
            if let a = viewController?.presentedViewController {
                return getTopCurrentVC(viewController: a)
            }
            
            return viewController
        }
        
        var result:UIViewController?
        var fontResponder:UIResponder? = window?.subviews.first
        
        fontResponder = fontResponder?.next
        
        if let a = fontResponder as? UIViewController {
            result = getTopCurrentVC(viewController: a)
        }else{
            result = window?.rootViewController
            if let r = result {
                result = getTopCurrentVC(viewController: r)
            }
        }
        
        return result
    }
    
    
    public func transfer(mov videoUrl:URL?, toMP4 completeBlock:((_ resultUrl:URL?) -> Void)?){
        if (videoUrl == nil) {
            completeBlock?(nil)
        }
        
        let videoAsset = AVAsset(url: videoUrl!)
        
        let exprotSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetMediumQuality)
        exprotSession?.shouldOptimizeForNetworkUse = true
        exprotSession?.outputFileType = AVFileType.mp4
        
        var basePath = NSTemporaryDirectory()
        
        basePath = basePath.appending("videos")
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: basePath) {
            do{
                try fileManager.createDirectory(atPath: basePath, withIntermediateDirectories: true, attributes: nil)
            }catch{
                completeBlock?(nil)
                return
            }
        }
        
        
        var compressedVideoUrl:URL?
        compressedVideoUrl = URL(fileURLWithPath: basePath)
        compressedVideoUrl = compressedVideoUrl?.appendingPathComponent("MovToMP4.mp4")
        
        if fileManager.fileExists(atPath: compressedVideoUrl!.path) {
            
            do{
                try fileManager.removeItem(at: compressedVideoUrl!)
            }catch{
                print("remove exist mp4 file failed")
            }
        }
        
        exprotSession?.outputURL = compressedVideoUrl
        exprotSession?.exportAsynchronously(completionHandler: { [weak exprotSession] in
            print(exprotSession!.status.rawValue)
            print("video transfer success\n \(compressedVideoUrl) compressedVideoUrl\n\(try! fileManager.attributesOfItem(atPath: compressedVideoUrl!.path))\n")
            DispatchQueue.main.async {
                completeBlock?(compressedVideoUrl)
            }
        })
        
    }
}

public enum FontSizeType {
    
    case maxSmall
    case small
    case titleSize
    case normal
    case big
    case large
    
    
    public func font(bold: Bool = false) -> UIFont {
        var fontSize: CGFloat = 0
        switch self {
            
        case .maxSmall:
            fontSize = 12
        case .small:
            fontSize = 14
        case .normal:
            fontSize = 16
        case .titleSize:
            fontSize = 17
        case .big:
            fontSize = 19
        case .large:
            fontSize = 21
        }
        
        return bold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
    }
}
